import { CloseCircleOutlined, EditOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { message, Modal } from 'antd';
import Button from 'antd/es/button';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { delOrganization } from '../../../../servers/servers';
import { OrganizationOperation } from './OrganizationOperation';

interface OrganizationHandlerProp {
  refresh: () => any;
}

interface OrganizationHandlerState extends OrganizationHandlerProp {
  visible: boolean;
  x: number;
  y: number;
  caption: string;
  key: string | number;
  isRoot: boolean;
}

export interface OrganizationHandleShowArg {
  position: [number, number];
  caption: string;
  key: string | number;
  isRoot: boolean;
}

/**
 * 职责： 构造树节点hover时的组织操作块及其交互
 */
export class OrganizationHandler extends React.Component<
  OrganizationHandlerProp,
  OrganizationHandlerState
> {
  private operationRef: React.RefObject<OrganizationOperation>;

  constructor(prop: OrganizationHandlerProp) {
    super(prop);
    this.operationRef = React.createRef();
    this.state = {
      ...prop,
      visible: false,
      x: 0,
      y: 0,
      caption: '',
      key: 0,
      isRoot: true,
    };
  }

  public show(arg: OrganizationHandleShowArg): void {
    this.setState({
      visible: true,
      x: arg.position[0],
      y: arg.position[1],
      caption: arg.caption,
      key: arg.key,
      isRoot: arg.isRoot,
    });
  }

  public hide(): void {
    this.setState({
      visible: false,
    });
  }

  private create() {
    this.operationRef.current?.open('create', {
      organizationId: this.state.key as number,
    });
  }

  private modify() {
    this.operationRef.current?.open('modify', {
      organizationName: this.state.caption,
      organizationId: this.state.key as number,
    });
  }

  private delete() {
    Modal.confirm({
      content: '删除组织机构后无法恢复，确定删除吗',
      onOk: () => {
        delOrganization(this.state.key as number)
          .then(res => {
            message.success('删除成功');
            this.state.refresh();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  render() {
    const { visible, x, y, caption, isRoot } = this.state;
    const { operationRef } = this;
    return (
      <>
        {visible && (
          <div className="organization-handler" style={{ top: y, left: x }}>
            <div className="organization-title">{caption}</div>
            {checkPermission('/account/organization/add') && (
              <>
                <Button
                  className="organization-handler-btn"
                  type="primary"
                  icon={<PlusCircleOutlined />}
                  onClick={() => {
                    this.create();
                  }}
                >
                  新建子组织
                </Button>
                <br />
              </>
            )}
            {checkPermission('/account/organization/modify') && (
              <>
                <Button
                  className="organization-handler-btn"
                  type="primary"
                  icon={<EditOutlined />}
                  onClick={() => {
                    this.modify();
                  }}
                >
                  编辑组织
                </Button>
                <br />
              </>
            )}
            {!isRoot && checkPermission('/account/organization/delete') && (
              <Button
                className="organization-handler-btn"
                type="ghost"
                icon={<CloseCircleOutlined />}
                onClick={() => {
                  this.delete();
                }}
              >
                删除组织
              </Button>
            )}
          </div>
        )}
        <OrganizationOperation
          ref={operationRef}
          callback={() => {
            this.state.refresh();
          }}
        />
      </>
    );
  }
}
